<template>
  <el-dialog
    title="修改密码"
    :visible.sync="showPwdModal"
    :close-on-click-modal="false"
    @close="cancel"
    width="450px"
  >
    <div v-loading="loading" element-loading-text="数据提交中...">
      <el-form
        label-width="110px"
        label-position="left"
        :model="formData"
        :rules="rules"
        ref="forms"
      >
        <el-form-item label="原密码" prop="oldPwd">
          <el-input size="small" placeholder="请输入原密码" show-password v-model="formData.oldPwd" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input size="small" placeholder="请输入新密码" show-password v-model="formData.newPwd" />
        </el-form-item>
        <el-form-item label="确认新密码" prop="newPwd1">
          <el-input size="small" placeholder="请确认新密码" show-password v-model="formData.newPwd1" />
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="cancel">取消</el-button>
      <el-button :loading="loading" size="mini" type="primary" @click="onChangePwd">确定修改</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { _changePwd } from '_api'

export default {
  data() {
    const checkPass = (rule, value, callback) => {
      if (value && value != this.formData.newPwd) {
        callback(new Error('和新密码不一致'))
      } else {
        callback()
      }
    }
    return {
      showPwdModal: false,
      loading: false,
      formData: {
        oldPwd: '',
        newPwd: '',
        newPwd1: '',
      },
      rules: {
        oldPwd: [{ required: true, message: '原密码必填' }],
        newPwd: [
          { required: true, message: '新密码必填' },
          { min: 6, message: '最少8位数字和英文组成' },
        ],
        newPwd1: [
          { required: true, message: '请确认新密码' },
          { validator: checkPass, trigger: 'blur' },
        ]
      }
    }
  },

  methods: {
    //修改密码
    onChangePwd() {
      this.$refs.forms.validate((valid) => {
        if (valid) {
          this.loading = true
          _changePwd({
            oldPwd: this.formData.oldPwd,
            newPwd: this.formData.newPwd,
          }).then(() => {
            this.cancel()
            this.$message.success('修改密码成功，请重新登录')
            this.$router.replace('/login')
          })
        }
      })
    },
    //取消弹框
    cancel() {
      this.loading = false
      this.showPwdModal = false
      this.$refs.forms.resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
</style>